package cn.jdemo.ref.SoftReference;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 设置 -Xms2M -Xmx3M
 */
public class Demo01 {
    private static List<Object> list = new ArrayList<>();

    public static void main(String[] args) {
        testSoftReference();
    }

    /**
     * 输出:
     * Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
     * 	at cn.jdemo.ref.SoftReference.Demo01.testSoftReference2(Demo01.java:34)
     * 	at cn.jdemo.ref.SoftReference.Demo01.main(Demo01.java:12)
     */
    private static void testSoftReference2() {

        List<Object> list = new ArrayList<>();
        byte[] buff = null;
        for (int i = 0; i < 10; i++) {
            buff = new byte[1024 * 1024];
            SoftReference<byte[]> sr = new SoftReference<>(buff);
            list.add(sr);
        }

        System.gc(); //主动通知垃圾回收

        for(int i=0; i < list.size(); i++){
            Object obj = ((SoftReference) list.get(i)).get();
            System.out.println(obj);
        }

        System.out.println("buff: " + buff.toString());
    }

    /**
     * 输出: ????
     * Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
     * 	at cn.jdemo.ref.SoftReference.Demo01.testSoftReference(Demo01.java:67)
     * 	at cn.jdemo.ref.SoftReference.Demo01.main(Demo01.java:12)
     */
    private static void testSoftReference() {
        byte[] buff = null;
        for (int i = 0; i < 10; i++) {
            buff = new byte[1024 * 1024];
            SoftReference<byte[]> sr = new SoftReference<>(buff);
            list.add(sr);
        }

        System.gc(); //主动通知垃圾回收

        for(int i=0; i < list.size(); i++){
            Object obj = ((SoftReference) list.get(i)).get();
            System.out.println(obj);
        }
    }
}
